/** @format */

import axios from 'axios-miniprogram'
import { useCache } from '../composables/useCache'
import { buildDefaultUrl } from '../utils/commonUtils'
import { GiteeService } from './giteeService'

export class UserService {
  // 缓存 openid
  openIdCache = useCache('openid')

  giteeService = new GiteeService()
  /**
   * 取得用户信息
   */
  async getUser() {
    const opendId = await this.getOpenId()
    const userInfo = await this.giteeService.getFileContentByUrl(
      buildDefaultUrl(this.buildUserKey(opendId)),
      true
    )

    userInfo.opendId = opendId
    return userInfo
  }

  async updateUser(userInfo) {
    const opendId = await this.getOpenId()
    return this.giteeService.updateFileContentByUrl(
      buildDefaultUrl(this.buildUserKey(opendId)),
      userInfo
    )
  }

  /**
   * 异步获取用户的 OpenID
   */
  async getOpenId() {
    // 先取得缓存中的 openid， 如果没有则通过接口取得
    let openId = this.openIdCache.getItem()
    if (openId) return openId

    // const accountInfo = uni.getAccountInfoSync()

    const { code } = await uni.login()
    // 通过接口取得 openid
    // http://m-scrm-cn-test.geely-test.com
    const res = await axios.get('https://m-scrm-cn-test.geely-test.com/api/demo/token', {
      code,
    })
    openId = res.data.openid
    this.openIdCache.setItem(openId)
    return openId
  }

  async getLoginCode() {
    return new Promise((resolve, reject) => {
      uni.login({
        success: (res) => {
          resolve(res.code)
        },
        fail: (err) => {
          reject(err)
        },
      })
    })
  }

  buildUserKey(openId) {
    return `user/${openId}`
  }
}
